<template>
    <div class="tech-forum">
        <!-- 顶部导航栏 -->
        <NavBar />

        <!-- 主要内容区 -->
        <main class="forum-main">
            <div class="main-container">
                <!-- 左侧内容区 -->
                <div class="content-left">
                    <!-- 问题分类筛选 -->
                    <div class="postFilters">
                        <div class="filterTabs">
                            <span :class="{ active: activeTab === 'newest' }" @click="changeTab('newest')">最新问题</span>
                            <span :class="{ active: activeTab === 'hot' }" @click="changeTab('hot')">热门问题</span>
                            <span :class="{ active: activeTab === 'unanswered' }"
                                @click="changeTab('unanswered')">待回答</span>
                            <div class="searchBox">
                                <input v-model="searchBoard" placeholder="搜索标签" @input="handleBoardSearchInput" />
                                <button @click="searchByBoard">搜索</button>
                            </div>
                        </div>
                        <div class="boardFilter">
                            <span class="board" v-for="board in popularBoards" :key="board.id"
                                @click="filterByBoard(board)" :class="{ selected: board.selected }">
                                {{ board.boardName }}
                            </span>
                        </div>
                    </div>

                    <!-- 帖子列表 -->
                    <div class="postList">
                        <div v-if="posts.length === 0" class="empty-post">
                            暂无技术问题，欢迎踊跃参与互动~
                        </div>
                        <div class="postItem" v-for="post in posts" :key="post.postId" v-else @click="goToPostDetail(post.postId)">
                            <div class="stats" @click.stop>
                                <div class="votes">
                                    <span class="count">{{ post.visitCount }}</span>
                                    <span>浏览量</span>
                                </div>
                                <div class="answers" :class="{ answered: post.replyCount > 0 }">
                                    <span class="count">{{ post.replyCount }}</span>
                                    <span>回答量</span>
                                </div>
                                <div class="views">
                                    <span class="count">{{ post.likeCount }}</span>
                                    <span>点赞量</span>
                                </div>
                            </div>
                            <div class="content">
                                <h3 class="title">
                                    <router-link :to="`/forum/detail/${post.postId}`">{{ post.postTitle }}</router-link>
                                </h3>
                                <div class="excerpt">{{ post.postContent }}</div>
                                <div class="meta">
                                    <div class="boards">
                                        <span class="board" v-for="board in post.boards.split('、')" :key="board">
                                            {{ board }}
                                        </span>
                                    </div>
                                    <div class="user-info">
                                        <span class="time">{{ post.time }}</span>
                                        <router-link :to="{ path: '/forum/profile', query: { userId: post.userId } }" class="user" @click.stop>
                                            <img :src="post.profilePicture || defaultAvatar" alt="用户头像">
                                            {{ post.nickName }}
                                        </router-link>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 分页控件 -->
                    <el-pagination background size="small" layout="total, sizes, prev, pager, next, jumper"
                        :total="total" v-model:current-page="params.pageNum" v-model:page-size="params.pageSize"
                        :page-sizes="[5, 10, 15, 20]" @size-change="handleSizeChange"
                        @current-change="handleCurrentChange" />
                </div>

                <!-- 右侧边栏 -->
                <div class="sidebarRight">
                    <!-- 热门标签 -->
                    <div class="sidebarWidget">
                        <h3 class="widgetTitle">热门标签</h3>
                        <div class="boardCloud">
                            <router-link v-for="board in hotBoards" :key="board.boardId"
                                :to="{ path: '/forum/tag', query: { tagId: board.boardId } }">
                                {{ board.boardName }}
                            </router-link>
                        </div>
                    </div>

                    <!-- 活跃用户 -->
                    <div class="sidebarWidget">
                        <h3 class="widgetTitle">导航菜单</h3>
                        <div class="nav-menu">
                            <router-link to="/forum/help" class="menu-item">
                                <i class="icon-help"></i>
                                帮助中心
                            </router-link>
                            <!-- 其他现有菜单项保持原样 -->
                        </div>
                    </div>
                    <div class="sidebarWidget">
                        <h3 class="widgetTitle">活跃用户</h3>
                        <div class="activeUsers">
                            <div class="user" v-for="user in hotUsers" :key="user.userId">
                                <router-link :to="{ path: '/forum/profile', query: { userId: user.userId } }" @click.stop>
                                    <img :src="user.profilePicture"  alt="用户头像">
                                    <span class="name">{{ user.nickName }}</span>
                                    <span class="postCount">{{ user.postCount }}</span>
                                </router-link>
                            </div>
                        </div>
                    </div>

                    <!-- 统计数据 -->
                    <div class="sidebar-widget stats-widget">
                        <h3 class="widgetTitle">社区统计</h3>
                        <div class="statsContainer">
                            <div class="statItem">
                                <span class="count">{{ totalPosts }}</span>
                                <span class="label">问题</span>
                            </div>
                            <div class="statItem">
                                <span class="count">{{ totalAnswers }}</span>
                                <span class="label">回答</span>
                            </div>
                            <div class="statItem">
                                <span class="count">{{ totalUsers }}</span>
                                <span class="label">用户</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>

        <!-- 底部浮动按钮 -->
        <div class="floatingActions">
            <button class="fab askPost" @click="goToAskPost" title="提问">
                <el-icon><QuestionFilled /></el-icon>
            </button>
            <button class="fab feedback" @click="goToFeedback" title="反馈建议">
                <el-icon><ChatLineRound /></el-icon>
            </button>
        </div>
    </div>
</template>

<script setup>
import { QuestionFilled, ChatLineRound } from '@element-plus/icons-vue'
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { getBoardListService, getNewestPosts, getHotPosts, getUnansweredPosts, getHotBoardListService } from '@/apis/board.js';
import { getHotUserListService, getTotalService } from '@/apis/user.js';
import { ElMessage } from 'element-plus';
import { reactive } from "vue";
import { getToken } from '@/utils/cookie';

// 默认头像
const defaultAvatar = ref('@/assets/images/avatar01.png');

// Reactive data
const searchQuery = ref('');
const searchBoard = ref('');
const activeTab = ref('newest');
const posts = ref([]);
const total = ref(0);

const params = reactive({
    pageNum: 1,
    pageSize: 10,
    roleName: ''
});

const popularBoards = ref([]);
const boardLoading = ref(false);
const boardError = ref(null);

const hotBoards = ref([]);
const hotUsers = ref([]);

const totalPosts = ref(0);
const totalAnswers = ref(0);
const totalUsers = ref(0);

const router = useRouter();
let boardSearchTimer = null;

// 跳转到帖子详情页
const goToPostDetail = (postId) => {
    if (!postId) {
        ElMessage.warning('帖子ID不能为空');
        return;
    }
    router.push(`/forum/detail/${postId}`);
};
// Methods
const fetchBoardList = async () => {
    boardLoading.value = true;
    boardError.value = null;
    try {
        const res = await getBoardListService({
            boardName: searchBoard.value,
            pageNum: params.pageNum,
            pageSize: params.pageSize
        });
        popularBoards.value = res.rows.map(board => ({
            ...board,
            selected: false
        }));
        total.value = res.total;
    } catch (error) {
        boardError.value = error.message || '获取标签列表失败';
        console.error('获取标签列表失败:', error);
        ElMessage.error('获取标签列表失败');
    } finally {
        boardLoading.value = false;
    }
};

const searchByBoard = () => {
    params.pageNum = 1;
    loadBoards();
};

const handleBoardSearchInput = () => {
    clearTimeout(boardSearchTimer);
    boardSearchTimer = setTimeout(() => {
        params.pageNum = 1;
        loadBoards();
    }, 300);
};

const changeTab = (tab) => {
    activeTab.value = tab;
    params.pageNum = 1;
    loadPosts();
};

const filterByBoard = (clickedBoard) => {
    popularBoards.value = popularBoards.value.map(board => {
        if (board.boardId === clickedBoard.boardId) {
            return {
                ...board,
                selected: !board.selected
            };
        }
        return board;
    });
    params.pageNum = 1;
    loadPosts();
};

const loadBoards = () => {
    boardLoading.value = true;
    getBoardListService({
        boardName: searchBoard.value,
        pageNum: params.pageNum,
        pageSize: params.pageSize
    }).then(res => {
        popularBoards.value = res.rows.map(board => ({
            ...board,
            selected: false
        }));
        total.value = res.total;
    }).catch(error => {
        ElMessage.error('获取标签列表失败');
    }).finally(() => {
        boardLoading.value = false;
    });
};

const loadPosts = () => {
    const selectedBoards = popularBoards.value
        .filter(board => board.selected)
        .map(board => String(board.boardId));

    const queryParams = {
        pageNum: params.pageNum,
        pageSize: params.pageSize,
        boards: selectedBoards.join(',')
    };

    let apiCall;
    if (activeTab.value === 'newest') {
        apiCall = getNewestPosts(queryParams);
    } else if (activeTab.value === 'hot') {
        apiCall = getHotPosts(queryParams);
    } else if (activeTab.value === 'unanswered') {
        apiCall = getUnansweredPosts(queryParams);
    }

    apiCall.then(res => {
        const processedPosts = res.rows.map(post => {
            const content = post.postContent || '';
            const excerptLength = Math.ceil(content.length * 0.2);
            const timeWithOutT = post.time ? post.time.replace('T', ' ') : '';
            return {
                ...post,
                postContent: content.substring(0, excerptLength) +
                    (content.length > excerptLength ? '...' : ''),
                profilePicture: post.profilePicture || defaultAvatar.value,
                time: timeWithOutT // 将处理后的时间赋值给time属性
            };
        });

        posts.value = processedPosts;
        total.value = res.total;
    }).catch(error => {
        console.error('获取帖子列表失败:', error);
        ElMessage.error('获取帖子列表失败');
    });
};

const handleSizeChange = (newSize) => {
    params.pageSize = newSize;
    params.pageNum = 1;
    if (activeTab.value === 'newest' || activeTab.value === 'hot' || activeTab.value === 'unanswered') {
        loadPosts();
    } else {
        loadBoards();
    }
};

const handleCurrentChange = (newPage) => {
    params.pageNum = newPage;
    if (activeTab.value === 'newest' || activeTab.value === 'hot' || activeTab.value === 'unanswered') {
        loadPosts();
    } else {
        loadBoards();
    }
};

const goToAskPost = () => {
    if (!getToken()) {
        ElMessage.warning('请先登录后再提问');
    } else {
        router.push('/forum/ask');
    }
};

const goToProfile = () => {
    console.log('前往个人中心');
};

const goToFeedback = () => {
    router.push('/forum/feedback');
};

const goToLogin = () => {
    router.push('/forum/login');
};

// Lifecycle hooks
onMounted(() => {
    fetchBoardList();
    loadPosts();

    getHotBoardListService()
        .then(res => {
            hotBoards.value = res.map(board => ({
                ...board
            }));
        })
        .catch(error => {
            console.error('获取热门标签列表失败:', error);
            ElMessage.error('获取热门标签列表失败');
        });

    getHotUserListService()
        .then(res => {
            hotUsers.value = res.map(user => ({
                ...user,
                profilePicture: user.profilePicture || defaultAvatar.value
            }));
        })
        .catch(error => {
            console.error('获取活跃用户列表失败:', error);
            ElMessage.error('获取活跃用户列表失败');
        });

    getTotalService()
        .then(res => {
            totalPosts.value = res.postCount;
            totalAnswers.value = res.replyCount;
            totalUsers.value = res.userCount;
        })
        .catch(error => {
            console.error('获取社区统计失败:', error);
            ElMessage.error('获取社区统计失败');
        });
});
</script>

<style scoped lang="scss">
.tech-forum {
    font-family: 'Segoe UI', Arial, sans-serif;
    color: #333;
    background: #f5f7fa;
    min-height: 100vh;
}

.forum-main {
    max-width: 1200px;
    margin: 20px auto;
    padding: 0 20px;
}

/* 主容器布局 */
.main-container {
    display: flex;
    gap: 24px;
    align-items: flex-start;

    @media (max-width: 992px) {
        flex-direction: column;
        gap: 20px;
    }
}

/* 左侧内容区 */
.content-left {
    flex: 1;
    min-width: 0;
    display: flex;
    flex-direction: column;
    gap: 24px;
}

/* 右侧边栏 */
.sidebarRight {
    width: 300px;
    display: flex;
    flex-direction: column;
    gap: 24px;
    position: sticky;
    top: 90px;

    @media (max-width: 992px) {
        width: 100%;
        position: static;
        flex-direction: row;
        flex-wrap: wrap;

        >* {
            flex: 1;
            min-width: 280px;
        }
    }

    @media (max-width: 600px) {
        >* {
            min-width: 100%;
        }
    }
}

/* 公共卡片样式 */
.postFilters,
.sidebarWidget,
.postList {
    background: white;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    border: 1px solid #eee;
}

/* 提问按钮 */
.askPostBox {
    .btn-primary {
        background: linear-gradient(135deg, #32C5FF 0%, #0095ff 100%);
        color: white;
        border: none;
        padding: 10px 20px;
        border-radius: 8px;
        cursor: pointer;
        display: inline-flex;
        align-items: center;
        gap: 8px;
        font-weight: 500;
        transition: all 0.3s ease;

        &:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 149, 255, 0.2);
        }
    }
}

/* 筛选区域 - 与右侧热门标签对齐 */
.postFilters {
    padding: 20px;

    .filterTabs {
        display: flex;
        gap: 16px;
        margin-bottom: 16px;
        align-items: center;

        span {
            cursor: pointer;
            color: #666;
            padding: 6px 0;
            position: relative;

            &.active {
                color: #007bff;
                font-weight: 600;

                &::after {
                    content: '';
                    position: absolute;
                    bottom: 0;
                    left: 0;
                    width: 100%;
                    height: 2px;
                    background-color: #007bff;
                }
            }
        }

        .searchBox {
            margin-left: auto;
            display: flex;

            input {
                padding: 8px 12px;
                border: 1px solid #ddd;
                border-radius: 4px 0 0 4px;
                width: 200px;
            }

            button {
                padding: 8px 12px;
                background: #f8f9fa;
                border: 1px solid #ddd;
                border-left: none;
                border-radius: 0 4px 4px 0;
                cursor: pointer;
            }
        }
    }

    .boardFilter {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;

        .board {
            background: #f8f9fa;
            padding: 6px 12px;
            border-radius: 16px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.2s ease;
            border: 1px solid #e0e0e0;

            &.selected {
                background: #007bff;
                color: white;
                border-color: #007bff;
            }
        }
    }
}

/* 帖子列表 - 与右侧活跃用户对齐 */
.postList {
    padding: 16px;

    .empty-post {
        padding: 40px 20px;
        text-align: center;
        color: #999;
    }

    .postItem {
        padding: 20px;
        border-bottom: 1px solid #f0f0f0;
        display: flex;
        gap: 20px;
        transition: all 0.3s ease;

        &:last-child {
            border-bottom: none;
        }

        &:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
        }

        .stats {
            width: 90px;
            text-align: center;
            flex-shrink: 0;

            >div {
                margin-bottom: 12px;

                &:last-child {
                    margin-bottom: 0;
                }

                .count {
                    font-weight: bold;
                    display: block;
                    font-size: 18px;
                }

                span:last-child {
                    font-size: 12px;
                    color: #999;
                }

                &.answers.answered {
                    color: #28a745;
                }
            }
        }

        .content {
            flex: 1;

            .title {
                margin: 0 0 8px 0;
                font-size: 18px;

                a {
                    color: #333;
                    text-decoration: none;

                    &:hover {
                        color: #007bff;
                    }
                }
            }

            .excerpt {
                color: #666;
                margin: 8px 0 12px;
                font-size: 14px;
                line-height: 1.6;
            }

            .meta {
                display: flex;
                justify-content: space-between;
                align-items: center;
                font-size: 13px;

                .boards {
                    display: flex;
                    gap: 8px;

                    .board {
                        background: #f8f9fa;
                        padding: 4px 8px;
                        border-radius: 4px;
                        font-size: 12px;
                    }
                }

                .user-info {
                    display: flex;
                    align-items: center;
                    gap: 8px;
                    color: #999;

                    .user {
                        display: flex;
                        align-items: center;
                        gap: 6px;
                        color: #666;
                        text-decoration: none;

                        img {
                            width: 24px;
                            height: 24px;
                            border-radius: 50%;
                            object-fit: cover;
                        }

                        &:hover {
                            color: #007bff;
                        }
                    }
                }
            }
        }
    }
}

/* 右侧小工具公共样式 */
.sidebarWidget {
    padding: 20px;

    .widgetTitle {
        margin: 0 0 16px 0;
        font-size: 18px;
        font-weight: 600;
        color: #333;
        padding-bottom: 12px;
        border-bottom: 1px solid #eee;
    }
}

/* 热门标签 */
.boardCloud {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;

    a {
        padding: 6px 12px;
        background: #f8f9fa;
        border-radius: 16px;
        font-size: 14px;
        color: #666;
        text-decoration: none;
        transition: all 0.2s ease;
        border: 1px solid #e0e0e0;

        &:hover {
            background: #007bff;
            color: white;
            border-color: #007bff;
        }
    }
}

/* 活跃用户 - 高度与左侧帖子列表匹配 */
.activeUsers {
    min-height: 400px;

    .user {
        padding: 10px 0;
        border-bottom: 1px solid #f0f0f0;

        &:last-child {
            border-bottom: none;
        }

        a {
            display: flex;
            align-items: center;
            gap: 12px;
            color: #666;
            text-decoration: none;

            &:hover {
                color: #007bff;

                .name {
                    color: #007bff;
                }
            }

            img {
                width: 32px;
                height: 32px;
                border-radius: 50%;
                object-fit: cover;
            }

            .name {
                flex: 1;
                font-size: 14px;
                transition: color 0.2s;
            }

            .postCount {
                background: #f0f0f0;
                padding: 2px 8px;
                border-radius: 10px;
                font-size: 12px;
            }
        }
    }
}

/* 社区统计 */
.statsContainer {
    display: flex;
    justify-content: space-around;
    text-align: center;

    .statItem {
        .count {
            font-size: 24px;
            font-weight: bold;
            color: #007bff;
            display: block;
            line-height: 1.2;
        }

        .label {
            font-size: 13px;
            color: #999;
        }
    }
}

/* 分页控件 */
.el-pagination {
    margin-top: 20px;
    justify-content: center;
}

/* 浮动按钮 */
.floatingActions {
    position: fixed;
    right: 24px;
    bottom: 24px;
    display: flex;
    flex-direction: column;
    gap: 12px;
    z-index: 100;

    .fab {
        width: 56px;
        height: 56px;
        border-radius: 50%;
        background: linear-gradient(135deg, #32C5FF 0%, #0095ff 100%);
        color: white;
        border: none;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        box-shadow: 0 4px 12px rgba(0, 149, 255, 0.2);
        transition: all 0.3s ease;

        &:hover {
            transform: scale(1.1);
            box-shadow: 0 6px 16px rgba(0, 149, 255, 0.3);
        }

        i {
            font-size: 20px;
        }
    }
}
</style>